<?php
include_once dirname(__FILE__).'/public_file_encode.class.php';
include_once dirname(dirname(__FILE__)).'/public_return.class.php';
include_once dirname(dirname(dirname(__FILE__))) .'/nn_logic/file_encode/file_encode.class.php';
include_once dirname(dirname(dirname(__FILE__))) .'/nn_logic/file_encode/file_encode_log.class.php';
include_once dirname(dirname(dirname(__FILE__))) .'/nn_logic/vod_media/vod_media.class.php';
include_once dirname(dirname(dirname(__FILE__))) .'/nn_logic/live/live_media.class.php';
include_once dirname(dirname(dirname(__FILE__))) .'/nn_logic/op_queue/op_queue.class.php';
include_once dirname(dirname(dirname(__FILE__))) .'/nn_logic/transcode/transcode_manufacturer_model.class.php';
include_once dirname(dirname(dirname(__FILE__))) .'/nn_logic/transcode/transcode_manufacturer.class.php';
include_once dirname(dirname(dirname(__FILE__))) .'/nn_logic/transcode/transcode_model.class.php';
include_once dirname(dirname(__FILE__)).'/ftp/ftp.class.php';
class nl_file_encode_execute extends nl_public_file_encode
{
    public $obj_message_log = null;
    
	public $arr_transcode_model = null;
	
	
    public function __construct($sp_id,$obj_message_log)
    {
        $this->obj_dc = nl_get_dc(array (
            'db_policy' => NL_DB_WRITE,
            'cache_policy' => NP_KV_CACHE_TYPE_MEMCACHE
        ));
        $this->sp_id = $sp_id;
        $this->obj_message_log =$obj_message_log;
    }
    
    /**
     * 初始化
     * @return Ambigous <unknown, Ambigous, mixed>|multitype:number
     */
    public function init()
    {
        $result_sp = $this->_get_sp_info($this->sp_id);
        if($result_sp['ret'] !=0)
        {
            return $result_sp;
        }
        if(!isset($this->arr_sp_config[$this->sp_id]['nns_config']['clip_file_encode_enable']) || $this->arr_sp_config[$this->sp_id]['nns_config']['clip_file_encode_enable'] !=1)
        {
            return $this->__return_data(1,"获取SP_ID为[".ORG_ID."]的基本配置信息不需要文件转码逻辑，跳出循环");
        }
        if(!isset($this->arr_sp_config[$this->sp_id]['nns_config']['clip_file_encode_model']) 
            || !in_array($this->arr_sp_config[$this->sp_id]['nns_config']['clip_file_encode_model'], array('1','2')))
        {
            return $this->__return_data(1,"获取SP_ID为[".ORG_ID."]不是新版转码逻辑，跳出循环");
        }
        return $result_sp;
    }
    
    /**
     * 初始化消息
     */
    public function set_task($task_id=null)
    {
        $result_init = $this->init();
        if($result_init['ret'] !=0)
        {
            return $result_init;
        }
        $max_num = (isset($this->arr_sp_config[$this->sp_id]['nns_config']['clip_encode_wait_max']) && (int)$this->arr_sp_config[$this->sp_id]['nns_config']['clip_encode_wait_max']>0) ? (int)$this->arr_sp_config[$this->sp_id]['nns_config']['clip_encode_wait_max'] : 5;
        $result_file_encode= nl_file_encode::check_state_num_by_sp($this->obj_dc, $this->sp_id,'1');
        if($result_file_encode['ret'] !=0)
        {
            return $this->__return_data(1,"获取SP_ID为[".$this->sp_id."]的状态为正在转码的文件[数据库执行失败".var_export($result_file_encode['reason'],true));
        }
        $ex_num = 0;
        $file_encode = null;
        if(isset($result_file_encode['data_info']) && is_array($result_file_encode['data_info']))
        {
            foreach ($result_file_encode['data_info'] as $file_encode_val)
            {
                $temp_str = empty($file_encode_val['nns_loadbalance_id']) ? 'empty' : $file_encode_val['nns_loadbalance_id'];
                if(!isset($file_encode[$temp_str]))
                {
                    $file_encode[$temp_str] = 1;
                }
                else
                {
                    $file_encode[$temp_str] ++;
                }
                $ex_num++;
            }
        }
        if($max_num > $ex_num)
        {
            $num_wait = $max_num - $ex_num;
            $result_wait = $this->get_encode_clip_task($num_wait,null,$file_encode);
        }
//         $result_resend = $this->re_set_task();
        $this->__return_data(0,'OK');
    }
    
    /**
     * 初始化消息
     */
    public function re_set_task($task_id=null)
    {
        $result_init = $this->init();
        if($result_init['ret'] !=0)
        {
            return $result_init;
        }
        $max_num = (isset($this->arr_sp_config[$this->sp_id]['nns_config']['clip_encode_fail_max']) && (int)$this->arr_sp_config[$this->sp_id]['nns_config']['clip_encode_fail_max']>0) ? (int)$this->arr_sp_config[$this->sp_id]['nns_config']['clip_encode_fail_max'] : 0;
        $max_time = (isset($this->arr_sp_config[$this->sp_id]['nns_config']['clip_encode_fail_max_ex']) && (int)$this->arr_sp_config[$this->sp_id]['nns_config']['clip_encode_fail_max_ex']>0) ? (int)$this->arr_sp_config[$this->sp_id]['nns_config']['clip_encode_fail_max_ex'] : 0;
        if($max_num <1 || $max_time<1)
        {
            return $this->__return_data(1,'不执行失败数据重发');
        }
        $result_clip_task_wait = nl_file_encode::get_info_by_state_sp($this->obj_dc, $this->sp_id,'1',$max_num,$max_time);
	    if($result_clip_task_wait['ret'] !=0 || empty($result_clip_task_wait['data_info']) || !is_array($result_clip_task_wait['data_info']))
	    {
	        return $result_clip_task_wait;
	    }
        return $this->get_encode_clip_task($max_num,$result_clip_task_wait);
    }
    
    /**
     * 获取转码状态
     * @return Ambigous
     */
    public function get_task_state()
    {
        $result_init = $this->init();
        if($result_init['ret'] !=0)
        {
            return $result_init;
        }
        $result_encode_doing = nl_file_encode::get_info_by_state_sp($this->obj_dc, $this->sp_id,'1');
        if($result_encode_doing['ret'] !=0 || empty($result_encode_doing['data_info']) || !is_array($result_encode_doing['data_info']))
        {
            return $result_encode_doing;
        }
        $arr_encode_doing = null;
        foreach ($result_encode_doing['data_info'] as $val)
        {
            $arr_encode_doing[$val['nns_loadbalance_id']][] = $val;
            $result_transcode_model = $this->get_transcode_model($val['nns_model_id'], $val['nns_id']);
        }
        $result_data = nl_transcode_load_balance::query_sp_info($this->obj_dc,$this->sp_id);
        if($result_data['ret'] !=0)
        {
            return $result_data;
        }
        $temp_result_data = null;
        if(isset($result_data['data_info']) && is_array($result_data['data_info']) && !empty($result_data['data_info']))
        {
            foreach ($result_data['data_info'] as $data_info)
            {
                $temp_result_data[$data_info['nns_id']] = $data_info;
            }
        }
        if(empty($temp_result_data) || !is_array($temp_result_data) || empty($arr_encode_doing) || !is_array($arr_encode_doing))
        {
            return $result_data;
        }
        foreach ($arr_encode_doing as $encode_doing_key=>$encode_doing_val)
        {
            if(!isset($temp_result_data[$encode_doing_key]))
            {
                continue;
            }
            $result = $this->execute('get_task_state',$encode_doing_val,$result_transcode_model['data_info'],$temp_result_data[$encode_doing_key]);
//             if($result['ret'] !=0)
//             {
//                 return $result;
//             }
        }
        return $this->__return_right_data(0,'ok');
    }
    
    
    public function live_to_media()
    {
        $sp_config = nl_sp::get_sp_config($this->obj_dc, $this->sp_id);
        if($sp_config['ret'] !=0)
        {
            $this->obj_message_log->msg("获取SP_ID为[".$this->sp_id."]的基本配置信息失败".var_export($sp_config['reason'],true));
            return ;
        }
        $this->sp_config = isset($sp_config['data_info']['nns_config']) ? $sp_config['data_info']['nns_config'] : null;
        if(!isset($this->sp_config['clip_file_encode_enable']) || $this->sp_config['clip_file_encode_enable'] !=1)
        {
            $this->obj_message_log->msg("获取SP_ID为[".ORG_ID."]的基本配置信息不需要文件转码逻辑，跳出循环");
            return ;
        }
    }
    
    
    /**
     * 转码执行开始
     */
    public function execute($str_func,$data_queue=null,$data_model=null,$arr_params=null)
    {
        $this->arr_sp_config[$this->sp_id]['nns_config']['clip_encode_model'] = (!isset($this->arr_sp_config[$this->sp_id]['nns_config']['clip_encode_model']) || strlen($this->arr_sp_config[$this->sp_id]['nns_config']['clip_encode_model']) <1) ? '0' :  $this->arr_sp_config[$this->sp_id]['nns_config']['clip_encode_model'];
        switch ($this->arr_sp_config[$this->sp_id]['nns_config']['clip_encode_model'])
        {
            case '0':
                include_once dirname(__FILE__).'/file_encode_ruima.class.php';
                $str_class = 'nl_file_encode_ruima';
                break;
            case '1':
                include_once dirname(__FILE__).'/file_encode_dayang.class.php';
                $str_class = 'nl_file_encode_dayang';
                break;
            case '2':
                include_once dirname(__FILE__).'/file_encode_yunshi.class.php';
                $str_class = 'nl_file_encode_yunshi';
                break;
            default:
                include_once dirname(__FILE__).'/file_encode_ruima.class.php';
                $str_class = 'nl_file_encode_ruima';
        }
        $obj_file_encode = new $str_class($this->obj_dc,$data_queue,$data_model,$this->arr_sp_config,$this->sp_id,$arr_params);

        $arr_function = get_class_methods($obj_file_encode);
        $arr_function = is_array($arr_function) ? $arr_function : array();
        
        if(!in_array($str_func, $arr_function))
        {
            return $this->__return_data(1,"未查询到转码方法class[{$str_class}]fuction[{$str_func}]");
        }
        $result = $obj_file_encode->$str_func();
        unset($obj_file_encode);
        return $result;
    }
    
    
	/**
	 * 处理等待转码的数据进度
	 */
	public function get_encode_clip_task($num,$result_clip_task_wait=null,$file_encode=null)
	{
	    $str_func = 'set_task';
	    if(!isset($result_clip_task_wait) || !is_array($result_clip_task_wait) || empty($result_clip_task_wait))
	    {
	        $str_func = 'set_task';
    	    $result_clip_task_wait = nl_file_encode::get_info_by_state_sp($this->obj_dc, $this->sp_id,'0',$num,$this->arr_sp_config[$this->sp_id]['nns_config']['clip_encode_fail_max_ex']);
    	    if($result_clip_task_wait['ret'] !=0 || empty($result_clip_task_wait['data_info']) || !is_array($result_clip_task_wait['data_info']))
    	    {
    	        return $result_clip_task_wait;
    	    }
	    }
	    if(!is_array($result_clip_task_wait['data_info']) || empty($result_clip_task_wait['data_info']))
	    {
	        return $this->__return_data(0,'ok query no data');
	    }
	    $result_encode_load = $result_encode_num = null;
	    if(isset($this->arr_sp_config[$this->sp_id]['nns_config']['transcode_load_balance_encode']) && $this->arr_sp_config[$this->sp_id]['nns_config']['transcode_load_balance_encode'] == '1')
        {
	        $result_encode_load = $this->get_load_balance_all_num(count($result_clip_task_wait['data_info']),$file_encode);
	    }
	    foreach ($result_clip_task_wait['data_info'] as $val)
	    {
	        $result_transcode_model = $this->get_transcode_model($val['nns_model_id'], $val['nns_id']);
	        if($result_transcode_model['ret'] !=0 || empty($result_transcode_model['data_info']))
	        {
	            continue;
	        }
	        $temp_data = null;
	        if(is_array($result_encode_load))
	        {
	            $temp_data = array_pop($result_encode_load);
	            $temp_data = isset($this->arr_transcode_load_balance[$temp_data]) ? $this->arr_transcode_load_balance[$temp_data] : null;
	        }
	        else 
	        {
	            continue;
	        }
	        $result_encode = $this->execute($str_func,$val,$result_transcode_model['data_info'],$temp_data);
            $this->obj_message_log->msg("执行结果[{$val['nns_id']}]".var_export($result_encode,true));
	    }
	    return $this->__return_data(0,'OK');
	}
	
	/**
	 * 文件转码队列删除
	 * @param unknown $task_id
	 */
	public function file_cancel($task_id=null)
	{
	    $result_init = $this->init();
	    $result_clip_task = nl_file_encode::query_by_ids($this->obj_dc, $task_id);
	    if($result_clip_task['ret'] !=0 || empty($result_clip_task['data_info']) || !is_array($result_clip_task['data_info']))
	    {
	        return $result_clip_task;
	    }
	    return $this->execute('cancel_task',$result_clip_task['data_info']);
	}
	
	/**
	 * 文件转码队列删除
	 * @param unknown $task_id
	 */
	public function file_del($task_id=null)
	{
	    $result_init = $this->init();
	    $result_clip_task = nl_file_encode::query_by_ids($this->obj_dc, $task_id);
	    if($result_clip_task['ret'] !=0 || empty($result_clip_task['data_info']) || !is_array($result_clip_task['data_info']))
	    {
	        return $result_clip_task;
	    }
	    return $this->execute('del_task',$result_clip_task['data_info']);
	}
	
	/**
	 * 获取文件转码状态
	 * @param unknown $task_id
	 */
	public function file_state($task_id=null)
	{
	    $result_clip_task_doing = nl_file_encode::get_info_by_state_sp($this->obj_dc, $this->sp_id,'1');
        if($result_clip_task_doing['ret'] !=0 || !isset($result_clip_task_doing['data_info']) || empty($result_clip_task_doing['data_info']))
        {
            continue;
        }
        return $this->execute('get_task_state',$result_clip_task_doing['data_info'][0]);
	}
	
	
	/**
	 * 获取转码模板数据
	 * @param unknown $nns_model_id
	 * @param unknown $nns_task_id
	 */
	public function get_transcode_model($nns_model_id,$nns_task_id)
	{
	    if(isset($this->arr_transcode_model[$nns_model_id]))
	    {
	        return $this->__return_data(0,'ok',$this->arr_transcode_model[$nns_model_id]);
	    }
	    $result_transcode_model = nl_transcode_model::query_other_by_id($this->obj_dc, $nns_model_id);
	    if($result_transcode_model['ret'] !=0)
	    {
	        $this->make_file_encode_log($nns_task_id, $result_transcode_model['reason']);
	        $result_edit = nl_file_encode::edit($this->obj_dc, array('nns_state'=>2), $nns_task_id);
	        if($result_edit['ret'] !=0)
	        {
	            $this->obj_message_log->msg("修改转码状态数据库执行失败".var_export($result_edit['reason'],true));
	            return $this->__return_data(1,"修改转码状态数据库执行失败".var_export($result_edit['reason'],true));
	        }
	    }
	    else if(!isset($result_transcode_model['data_info']) || empty($result_transcode_model['data_info']) || !is_array($result_transcode_model['data_info']))
	    {
	        $this->arr_transcode_model[$nns_model_id] = null;
	        $this->make_file_encode_log($nns_task_id, "查询转码模板ID数据为空为空");
	        $result_edit = nl_file_encode::edit($this->obj_dc, array('nns_state'=>5), $nns_task_id);
	        if($result_edit['ret'] !=0)
	        {
	            $this->obj_message_log->msg("修改转码状态数据库执行失败".var_export($result_edit['reason'],true));
	            return $this->__return_data(0,"修改转码状态数据库执行失败".var_export($result_edit['reason'],true));
	        }
	    }
	    else
	    {
	        $this->arr_transcode_model[$nns_model_id] = $result_transcode_model['data_info'];
	    }
	    return $this->__return_data(0,'ok',$this->arr_transcode_model[$nns_model_id]);
	}
	
	/**
	 * 插入转码日志
	 * @param unknown $file_encode_id
	 * @param unknown $nns_request_state
	 * @param string $nns_request_state
	 * @param unknown $nns_notify_state
	 * @param string $nns_notify_content
	 * @param unknown $nns_desc
	 */
	public function make_file_encode_log($file_encode_id,$nns_desc,$nns_request_state=0,$nns_notify_state=0,$nns_request_content='',$nns_notify_content='')
	{
	    if(strlen($file_encode_id) <1)
	    {
	        return $this->__return_data(1,'file_encode_id 参数为空不生成转码日志');
	    }
	    $arr_params = array(
	        'nns_id'=>np_guid_rand('file_encode_log'),
	        'nns_file_encode_id'=>$file_encode_id,
	        'nns_desc'=>$nns_desc,
	        'nns_request_state'=>$nns_request_state,
	        'nns_notify_state'=>$nns_notify_state,
	        'nns_request_content'=>$nns_request_content,
	        'nns_notify_content'=>$nns_notify_content,
	    );
	    return nl_file_encode_log::add($this->obj_dc, $arr_params);
	}
}
